﻿using cn.ys.ysdatatransfer.business;
using cn.Ysserver;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Xml;
using System.Threading.Tasks;
using System.Security.Cryptography;
using System.Windows.Forms;
using org.eclipse.paho.client.mqttv3.@internal;
using org.eclipse.paho.client.mqttv3;
using org.eclipse.paho.client.mqttv3.logging;
using org.eclipse.paho.client.mqttv3.persist;
using org.eclipse.paho.client.mqttv3.util;
using cn.Ysserver.entity;
using cn.Ysserver.impl;
using cn.Ysserver.Interface;
using cn.Ysserver.utils;
using System.Threading;
using System.IO;
using System.Text.RegularExpressions;
using com.force.json;

namespace Ys4GClient
{
    public partial class login : Form
    {
        public static login mInstance;
        private YsCloudClient mYsCloudClient;
        private Ys_callback mYsCloudClientCallback;

        public login()
        {
            mInstance = this;
            System.Console.WriteLine("service address:" + MqttPropertise.SERVER_ADDRESS);
            mYsCloudClient = Program.ysCloudClient;
            mYsCloudClientCallback = new Ys_callback(this);
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
            this.Resize += Form1_Resize;
        }

        private class Ys_callback : YsCloudMqttCallbackAdapter
        {
            login mLogin;
            public Ys_callback(login mLogin)
            {
                this.mLogin = mLogin;
            }

            override
            public void onConnectAck(int returnCode, string description)
            {
                System.Console.WriteLine("onConnectAck:" + returnCode + description);
                if (returnCode == 2)
                {
                    mInstance.loginSuccess(); ;
                }
                else if (returnCode == 1)
                {
                    mInstance.loginFailure();
                }
            }
        }

        private void clickRegist()
        {
            if (!mInstance.IsDisposed)
            {
                mInstance.BeginInvoke(
                    (MethodInvoker)
                        delegate
                        {
                            new Register().Show();
                            this.Hide();
                            this.notifyIcon1.Visible = false;
                        }
                    );
            }
        }

        private void loginSuccess()
        {
            if (!mInstance.IsDisposed)
            {
                mInstance.BeginInvoke(
                    (MethodInvoker)
                        delegate
                        {
                            new main().Show();
                            this.Hide();
                            this.notifyIcon1.Visible = false;
                        }
                    );
            }
        }

        private void loginFailure()
        {
            if (!mInstance.IsDisposed)
            {
                mInstance.BeginInvoke(
                    (MethodInvoker)
                        delegate
                        {
                            MessageBox.Show("登录失败，请检查网络连接！");
                            login_loading.Visible = false;
                        }
                    );
            }
        }

        private void doconect()
        {
            login_loading.Visible = true;
            try
            {
                if (mYsCloudClient.is_mqtt_connected())
                {
                    mYsCloudClient.DisConnectUnCheck();
                }
            }
            catch (Exception e)
            {
             
            }
            mYsCloudClient.Connect(login_account.Text, login_password.Text, login_account.Text);
        }

        private void login_Load(object sender, EventArgs e)
        {
            login_loading.Visible = false;
            WinFormHint.Win32Utility.SetCueText(this.login_account, "请输入手机号");
            WinFormHint.Win32Utility.SetCueText(this.login_password, "请输入密码");
            readAccPassFromXML();
            if (login_account.Text.Length != 0)
            {
                login_rem.Checked = true;
            }
        }

        //加密
        private string encryption(string express)
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = "ys4g_client";//密匙容器的名称，保持加密解密一致才能解密成功
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
            {
                byte[] plaindata = Encoding.Default.GetBytes(express);//将要加密的字符串转换为字节数组
                byte[] encryptdata = rsa.Encrypt(plaindata, false);//将加密后的字节数据转换为新的加密字节数组
                return Convert.ToBase64String(encryptdata);//将加密后的字节数组转换为字符串
            }
        }

        //解密
        private string decrypt(string ciphertext)
        {
            try
            {
                CspParameters param = new CspParameters();
                param.KeyContainerName = "ys4g_client";
                using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
                {
                    byte[] encryptdata = Convert.FromBase64String(ciphertext);
                    byte[] decryptdata = rsa.Decrypt(encryptdata, false);
                    return Encoding.Default.GetString(decryptdata);
                }
            } catch(Exception e) {
                return "";
            }
        }

        private bool isTelNumber(String num)
        {
            return Regex.IsMatch(num, @"^((0?1[358]\d{9})|((0(10|2[1-3]|[3-9]\d{2}))?[1-9]\d{6,7}))$");
        }

        private void readAccPassFromXML()
        {
            String path = Environment.CurrentDirectory + "\\AccountPassword.xml";
            if (!File.Exists(path))
            {
                XmlTextWriter writeXml = new XmlTextWriter("AccountPassword.xml", Encoding.UTF8);
                writeXml.WriteStartDocument(false);
                writeXml.WriteStartElement("ACC_PASS");
                writeXml.WriteElementString("Account", "");
                writeXml.WriteElementString("Password", "");
                writeXml.WriteEndElement();
                writeXml.Flush();
                writeXml.Close();
            }
            //创建一个XmlTextReader对象，读取XML数据
            XmlTextReader xmlReader = new XmlTextReader("AccountPassword.xml");
            while (xmlReader.Read())
            {
                if (true == xmlReader.Name.Equals("Account"))
                {
                    login_account.Text = decrypt(xmlReader.ReadString().Trim());
                }

                if (true == xmlReader.Name.Equals("Password"))
                {
                    login_password.Text = decrypt(xmlReader.ReadString().Trim());
                }
            }
            xmlReader.Close();
        }

        private void saveAccPassToXml(String account, String password)
        {
            XmlTextReader xmlReader = new XmlTextReader("AccountPassword.xml");
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load("AccountPassword.xml");
            XmlNode acc_node = xmlDoc.GetElementsByTagName("Account").Item(0);
            acc_node.InnerText = account;
            XmlNode pass_node = xmlDoc.GetElementsByTagName("Password").Item(0);
            pass_node.InnerText = password;
            xmlDoc.Save("AccountPassword.xml");
        }

        private void login_btn_Click(object sender, EventArgs e)
        {
            String account = login_account.Text;
            String password = login_password.Text.Trim();
            if (account.Length == 0 || password.Length == 0)
            {
                MessageBox.Show("手机号或密码不能为空格！");
                return;
            }
            if (!isTelNumber(account))
            {
                MessageBox.Show("输入的手机号不合法！");
                return;
            }
            if (login_rem.Checked == true)
            {
                saveAccPassToXml(encryption(account), encryption(password));
            }
            else
            {
                saveAccPassToXml("", "");
            }
            JSONObject jsonObj = new JSONObject();
            jsonObj.Put("loginParam", account);
            jsonObj.Put("password", password);
            String ret = MyHttp.httpPost(Constant.LOGIN_URL, jsonObj.ToString());

            mYsCloudClient.setUsrCloudMqttCallback(mYsCloudClientCallback);
            Thread thr = new Thread(doconect);
            thr.Start();
        }

        private void rem_acc_pass_CheckedChanged(object sender, EventArgs e)
        {

        }

        private void login_loading_Click(object sender, EventArgs e)
        {

        }

        void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.Visible = false;
                this.notifyIcon1.Visible = true;
            }
        }

        private void 显示主界面ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Show();
        }

        private void 退出ToolStripMenuItem_Click_1(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
            }
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Visible = true;
            this.WindowState = FormWindowState.Normal;
            this.Show();
        }

        private void regist_btn_Click(object sender, EventArgs e)
        {
            clickRegist();
        }

        public void setRegistAccount(string account)
        {
            login_account.Text = account;
            login_password.Text = "";
        }
    }
}
